package com.sinbad.interview.solution.question02.case02;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

/**
 * 2. 单桶统计频率最大值
 *
 * @author sinbad.cheng
 * @since 2025-04-14 17:51
 */
public class BucketProcessor {
    private static final String BUCKET_FOLDER = "buckets";


    public static Map.Entry<Integer, Integer> getMostFrequentFromBucket(File file) throws IOException {
        Map<Integer, Integer> freqMap = new HashMap<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                int num = Integer.parseInt(line.trim());
                freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);
            }
        }

        return freqMap.entrySet().stream()
                .max(Map.Entry.comparingByValue())
                .orElse(null);
    }


    // 删除所有桶文件和目录
    public static void cleanUp() throws IOException {
        Path dir = Paths.get(BUCKET_FOLDER);
        if (Files.exists(dir)) {
            Files.walk(dir)
                    .sorted(Comparator.reverseOrder())
                    .map(Path::toFile)
                    .forEach(File::delete);
            System.out.println("临时桶文件清理完成");
        }
    }
}
